define(["angularAMD","moment"], function (angularAMD,moment) {
    angularAMD.service('B0206Service', ['$rootScope', '$filter', '$translate', 'config', 'MMWService', '$mdDialog', "$calculater",
        function($rootScope, $filter, $translate, config, $MMWService, $mdDialog, $calculater){
            this.init = function(machine,plot, type, parent, feedback){

                var mode ='trackOut';
                var tmpAbnormal_qty = 0;

                var tmpBadReason = [];
                var badCodeList = {};
                var badReasonInfo = [];

                var plotInfo = {}; // plot.info.get
                var badReasonInfo_backup = [],//不良原因備份
                    labor_detail_backup = [],//多人產量備份
                    production_inf_detail_backup = [],
                    machine_no;//生產資訊備份

                if(type=='line'){
                    machine_no = machine.area_no;
                }else{
                    machine_no = machine.machine_no;
                }

                //取得生產批資料
                var getInitInfo = function () {
                    var content = {
                        machine_no : machine_no,
                        plot_no: plot.plot_no,
                        op_seq : '',//
                        op_no :plot.op_no,
                        workstation_no:'',//
                        qty: '',
                        return_type:'2'
                    };
                    if(parent == 'B0214'){
                        content.mode = '1';
                    }
                    $MMWService.sendToSMESServer({
                        uri:'tcSMES.LotData.plot_info_get',
                        content : content,
                        success : function(data){
                            if(data.plot_info_get.length > 0){
                                plotInfo = data.plot_info_get[0];
                                if(plotInfo.workstation_detail[0].labor_detail.length == 0){
                                    $rootScope.showAlert($filter('translate')('B0206.showAlert.column7'));
                                } else {
                                    plotInfo.report_datetime = new Date();
                                    plotInfo.qty = plotInfo.workstation_detail[0].check_out_qty;
                                    plotInfo.good_qty = plotInfo.workstation_detail[0].check_out_qty;
                                    //計算不良原因總數
                                    plotInfo.total_abnormal_qty = 0;//報廢
                                    plotInfo.total_lack_qty = 0;//短少
                                    plotInfo.total_surplus_qty = 0;//多餘
                                    if(plotInfo.workstation_detail[0].abnormal_detail){
                                        plotInfo.workstation_detail[0].abnormal_detail.forEach(function(abnormal_detail){
                                            if(abnormal_detail.abnormal_type == '11'){
                                                plotInfo.total_surplus_qty  = $calculater.decimalAdd((+plotInfo.total_surplus_qty), (+abnormal_detail.defect_qty));
                                            } else if(abnormal_detail.abnormal_type == '12'){
                                                plotInfo.total_lack_qty  = $calculater.decimalAdd((+plotInfo.total_lack_qty), (+abnormal_detail.defect_qty));
                                            } else {
                                                plotInfo.total_abnormal_qty = $calculater.decimalAdd((+plotInfo.total_abnormal_qty), (+abnormal_detail.defect_qty));
                                            }
                                        });
                                    }
                                    //2018051601 modify by Dustdusk for M#45925:
                                    //良品數 = 『出站數量』 - 『不良品』 - 『短少』 + 『多餘』
                                    plotInfo.good_qty =  $calculater.decimalSub($calculater.decimalSub($calculater.decimalAdd((+plotInfo.good_qty), (+plotInfo.total_surplus_qty)), (+plotInfo.total_abnormal_qty)), (+plotInfo.total_lack_qty));
                                    if(!plotInfo.workstation_detail[0].machine_qty||plotInfo.workstation_detail[0].machine_qty==''){
                                        plotInfo.workstation_detail[0].machine_qty = 1;
                                    }
                                    //2018051601 modify by Dustdusk for M#45925:
                                    //物料使用量 = 『良品』 + 『不良品』 + 『短少』 = 『出站數量』 + 『多餘』
                                    var sum_qty = $calculater.decimalAdd((+plotInfo.qty),(+plotInfo.total_surplus_qty));
                                    for(var i=0; i<plotInfo.workstation_detail[0].materials_detail.length; i++){
                                        plotInfo.workstation_detail[0].materials_detail[i].use_qty = $calculater.decimalMutiple(sum_qty, plotInfo.workstation_detail[0].materials_detail[i].std_use_qty, 6);
                                    }

                                    //多人產量登入
                                    for(var i=0; i<plotInfo.workstation_detail[0].labor_detail.length; i++){
                                        plotInfo.workstation_detail[0].labor_detail[i].qty = plotInfo.qty ;
                                    }
                                    //plotInfo.workstation_detail[0].QTYACIO = plotInfo.qty *((+plotInfo.workstation_detail[0].C_Numerator)/(+plotInfo.workstation_detail[0].C_Denominator));
                                    openDialog(plotInfo);
                                }
                            } else {
                                $rootScope.showAlert('plot_info_get is empty');
                            }
                        }
                    });
                }();

                //回到出站畫面
                function backToTrackOut(dialog){
                    if(dialog.mode == 'badReason'){
                        dialog.badReasonInfo = badReasonInfo_backup.slice();
                        badReasonInfo_backup = [];

                        dialog.tmpBadReason = '';
                        dialog.tmpAbnormal_qty = '';
                    } else if(dialog.mode == 'multiple'){
                        dialog.plotInfo.workstation_detail[0].labor_detail = angular.merge([],labor_detail_backup);
                        labor_detail_backup = [];
                        dialog.tmpLabor_no = '';
                    } else if(dialog.mode == 'production_inf'){
                        dialog.plotInfo.production_inf_detail = angular.merge([],production_inf_detail_backup);
                        production_inf_detail_backup = [];
                    }
                    dialog.mode='trackOut';
                }

                //出站確認
                function trackOutConfirm(dialog) {
                    var abnormal_detail = [],
                        plot_info_detail= {},
                        materials_detail=[],
                        subop_employee_detail=[];

                    dialog.badReasonInfo.forEach(function (item) {
                        abnormal_detail.push({
                            abnormal_no:item.abnormal_no,
                            defect_qty:item.defect_qty
                        });
                    });

                    if(dialog.parent != 'B0214'){
                        dialog.plotInfo.workstation_detail[0].labor_detail.forEach(function(item){
                            subop_employee_detail.push({
                                employee_no:item.labor_no,
                                work_time:item.labor_time,
                                qty:item.qty
                            });
                        });
                    }

                    dialog.plotInfo.workstation_detail[0].materials_detail.forEach(function(item){
                        if(item.putinplace_type == '5')
                            return;

                        materials_detail.push({
                            materials_no:item.materials_no,
                            materials_plot_no:item.materials_plot_no,
                            actual_use_qty:item.use_qty,

                        });
                    });

                    plot_info_detail = {
                        report_datetime : dialog.plotInfo.sysdate_time,
                        machine_no : machine_no, //
                        plot_no : dialog.plotInfo.workstation_detail[0].plot_no,
                        op_seq : dialog.plotInfo.workstation_detail[0].op_seq,
                        op_no : dialog.plotInfo.workstation_detail[0].op_no,
                        workstation_no : '',
                        qty:dialog.plotInfo.qty,//20180418 modify by Dustdusk for 調整回傳數量，一律改為使用者輸入的數量
                        labor_hours : dialog.plotInfo.workstation_detail[0].labor_hours,
                        machine_hours : dialog.plotInfo.workstation_detail[0].machine_hours,
                        number_of_operators : dialog.plotInfo.workstation_detail[0].number_of_labor,//
                        plot_stamp : dialog.plotInfo.workstation_detail[0].plot_stamp,
                        abnormal_detail : abnormal_detail,
                        subop_employee_detail : subop_employee_detail,
                        materials_detail : materials_detail,
                        wait_reason_detail : dialog.plotInfo.wait_reason_detail,
                        machine_no_wip : dialog.plotInfo.machine_no_wip //設備編號
                    };

                    var content = {
                        report_datetime: plot_info_detail.report_datetime,
                        check_out_mode: '1',
                        check_out_type: '2',
                        plot_info_detail:[plot_info_detail],
                        production_inf_type : dialog.plotInfo.production_inf_type,
                        production_inf_detail:dialog.plotInfo.production_inf_detail
                    };

                    $MMWService.sendToSMESServer({
                        uri: 'tcSMES.clsSMES.plot_check_out_process_json',
                        content: content,
                        success: function (data) {
                            $rootScope.showToast(data.SysMsg);
                            dialog.hide();
                            if(feedback)
                                feedback();
                        }
                    });
                }

                //檢查出站資訊
                function ProductionParametersCheckProcess(dialog){
                    var defect_qty = 0;
                    dialog.badReasonInfo.forEach(function (item) {
                        if(item.abnormal_type != '11'){
                            //2018051601 modify by Dustdusk for M#45925: 調整良品不良品計算規則
                            defect_qty = defect_qty + (+item.defect_qty);
                        }
                    });
                    var content = {
                        handle_type : 'CHECK_OUT',
                        recordlist : [{
                            plot_no : dialog.plotInfo.workstation_detail[0].plot_no,
                            op_no : dialog.plotInfo.workstation_detail[0].op_no,
                            qty : dialog.plotInfo.qty,//20180418 modify by Dustdusk for 調整回傳數量，一律改為使用者輸入的數量
                            abnormal_detail:plotInfo.workstation_detail[0].abnormal_detail
                        }]
                    };

                    //20180510 modify by 李栋 for mantis#0046717
                    $MMWService.sendToSMESServer({
                        uri: 'tcSMES.clsProductPrarmeters.production_parameters_check_process_json',
                        content: content,
                        success: function (data) {
                            checkRule(data.query_result, dialog);
                        }
                    });
                }

                //根據結果結果呈現
                //rule_result : WARNNING / WAIT / PASS
                //20170517 modify by Dustdusk for SMES_ProductionParametersCheckProcess調整回傳內容
                function checkRule(query_result, dialog){
                    var warnning_msg = '';
                    query_result.forEach(function(plot_rule){
                        var plot_warnning_msg = '';
                        plot_rule.rule_detail.forEach(function(rule_detail){
                            if(rule_detail.rule_result == 'WARNNING'){
                                if(plot_warnning_msg == ''){
                                    plot_warnning_msg = plot_rule.plot_no + '<br>';
                                }
                                plot_warnning_msg += rule_detail.rule_message + '<br>';
                            } else if(rule_detail.rule_result == 'WAIT'){
                                //is_wait = true;
                                dialog.plotInfo.wait_reason_detail.push({reason_no:'Z901'});
                            }
                        });
                        warnning_msg += plot_warnning_msg;
                    });

                    if(warnning_msg != ''){
                        $rootScope.showConfirm(warnning_msg,
                            function(dialog){
                                dialog.hide();
                                trackOutConfirm(dialog);
                            }
                        )
                    } else {
                        trackOutConfirm(dialog);
                    }
                }

                //取得例外原因類別
                function genBadType(badReasonList){
                    var badTypeList = [];
                    var badType = '';
                    badReasonList.forEach(function(badReason){
                        if(badType!=badReason.reason_type){
                            badTypeList.push({
                                reason_type:badReason.reason_type,
                                reason_sub_type:badReason.reason_sub_type
                            });
                            badType = badReason.reason_type;
                        }
                    });

                    return badTypeList;
                }

                //轉換率計算
                function CaculatQTYACIO(qty, C_Numerator, C_Denominator){
                    var QTYACIO = $calculater.decimalMutiple((+qty), (+C_Numerator)/(+C_Denominator)),
                        C_Mode = plotInfo.workstation_detail[0].C_Mode,
                        C_Accuracy = Math.pow(10,plotInfo.workstation_detail[0].C_Accuracy||0)||1;
                    if(C_Mode == '0'){
                        //無條件進位
                        QTYACIO = Math.ceil(QTYACIO * C_Accuracy) / C_Accuracy;
                    } else if(C_Mode == '1'){
                        //無條件捨位
                        QTYACIO = Math.floor(QTYACIO * C_Accuracy) / C_Accuracy;
                    }
                    return QTYACIO;
                }

                //模製具壽命檢查
                function SMES_AccLifeCheck(machine_no, plotInfo, callback){
                    var content = {
                        recordlist : [{
                            op_no : plotInfo.workstation_detail[0].op_no,
                            plot_no: plotInfo.workstation_detail[0].plot_no,
                            machine_no: machine_no,
                            status:'1',
                            qty : plotInfo.qty
                        }
                    ]};
                    $MMWService.sendToSMESServer({
                        uri: 'tcSMES.clsAccessory.acc_life_check_json',
                        content : content,
                        success : function(data){
                            if(data.life_manage == '0'){
                                //警示
                                $rootScope.showConfirm(data.SysMsg, function(confirmDialog){
                                    confirmDialog.hide();
                                    if(callback)
                                        callback();
                                });
                            } else if(data.life_manage == '1'){
                                //暫停生產
                                $rootScope.showAlert(data.SysMsg);
                            } else if(data.life_manage == '2'){
                                //核准
                                if(callback)
                                    callback();
                            }
                        }
                    });
                }

                //生產信息收集檢查
                function productionInfValidate(production_inf_detail){
                    var msg = '';
                    production_inf_detail.forEach(function(item){
                        if(item.productioninf_value == undefined || item.productioninf_value ==''){
                            msg +=$filter('translate')('B0206.msg.productioninf_value_empty', item)+'<br>';
                        }
                    });
                    return msg;
                }

                //開窗
                var openDialog = function(plotInfo){
                    plotInfo.wait_reason_detail = [];
                    $mdDialog.dialog(
                        'module/moduleWIP/program/B02/B0206/B0206.html',
                        function(dialog){
                            return {
                                css_url:'module/moduleWIP/program/B02/B0206/B0206.css',
                                isRequire:plotInfo.production_inf_type=='2',
                                plotInfo:plotInfo,
                                mode : mode,
                                badCodeList:badCodeList,
                                tmpBadReason : tmpBadReason,
                                tmpAbnormal_qty: tmpAbnormal_qty,
                                badReasonInfo:plotInfo.workstation_detail[0].abnormal_detail,
                                parent:parent,
                                backToTrackOut:backToTrackOut,//返回出站報工畫面
                                tmpLabor_no: '',
                                showRuleYield: function(){
                                    return dialog.plotInfo.rule_yield_ls != '' || dialog.plotInfo.rule_yield_lcl !='';
                                },
                                trackOutInputQty: function(event, trackOutQty){
                                    var target = event.currentTarget;
                                    angular.element(target).addClass('is-focus');
                                    $calculater.open(function(num,calcDialog){
                                            if((+num) == 0){
                                                $rootScope.showAlert($filter('translate')('B0206.showAlert.column1'));
                                            } else if((+num)>dialog.plotInfo.workstation_detail[0].check_out_qty){
                                                $rootScope.showAlert($filter('translate')('B0206.msg.column1') + num + $filter('translate')('B0206.msg.column2') + dialog.plotInfo.workstation_detail[0].check_out_qty);
                                            } else{
                                                dialog.plotInfo.qty = num;

                                                //dialog.plotInfo.good_qty = num;
                                                if((+num)!=trackOutQty){
                                                    //2018051601 modify by Dustdusk for M#45925:
                                                    //物料使用量 = 『良品』 + 『不良品』 + 『短少』 = 『出站數量』 + 『多餘』
                                                    var sum_qty = $calculater.decimalAdd((+dialog.plotInfo.qty),(+dialog.plotInfo.total_surplus_qty));
                                                    for(var i=0; i<plotInfo.workstation_detail[0].materials_detail.length; i++){
                                                        plotInfo.workstation_detail[0].materials_detail[i].use_qty =
                                                            $calculater.decimalMutiple(sum_qty, plotInfo.workstation_detail[0].materials_detail[i].std_use_qty, 6);
                                                    }
                                                    //多人產量登入
                                                    for(var i=0; i<plotInfo.workstation_detail[0].labor_detail.length; i++){
                                                        if((+plotInfo.workstation_detail[0].labor_detail[i].qty)>num){
                                                            plotInfo.workstation_detail[0].labor_detail[i].qty = num;
                                                        }
                                                    }

                                                    //2018051601 modify by Dustdusk for M#45925:
                                                    //如果良品數 = 『出站數量』 - 『不良品』 - 『短少』 + 『多餘』 小於0則清空例外原因
                                                    if(((+num) + dialog.plotInfo.total_surplus_qty) < ((+dialog.plotInfo.total_abnormal_qty)+(+dialog.plotInfo.total_lack_qty))){
                                                        calcDialog.hide();
                                                        var total_abnormal_qty = dialog.plotInfo.total_abnormal_qty;
                                                        var total_surplus_qty = dialog.plotInfo.total_surplus_qty;
                                                        var total_lack_qty = dialog.plotInfo.total_lack_qty;
                                                        dialog.plotInfo.total_abnormal_qty = 0;
                                                        dialog.plotInfo.total_surplus_qty = 0;
                                                        dialog.plotInfo.total_lack_qty = 0;
                                                        dialog.badReasonInfo = [];
                                                        dialog.plotInfo.good_qty = num;
                                                        dialog.plotInfo.workstation_detail[0].QTYACIO = CaculatQTYACIO(dialog.plotInfo.good_qty, dialog.plotInfo.workstation_detail[0].C_Numerator, dialog.plotInfo.workstation_detail[0].C_Denominator);
                                                        $rootScope.showAlert($filter('translate')('B0206.msg.qty_less_than_abnormal_qty', {abnormal_qty:(total_abnormal_qty+total_lack_qty-total_surplus_qty)}));
                                                    } else {
                                                        //2018051601 modify by Dustdusk for M#45925:
                                                        //良品數 = 『出站數量』 - 『不良品』 - 『短少』 + 『多餘』
                                                        dialog.plotInfo.good_qty =  $calculater.decimalSub($calculater.decimalSub($calculater.decimalAdd((+num), (+dialog.plotInfo.total_surplus_qty)), (+dialog.plotInfo.total_abnormal_qty)), (+dialog.plotInfo.total_lack_qty));
                                                        dialog.plotInfo.workstation_detail[0].QTYACIO = CaculatQTYACIO(dialog.plotInfo.good_qty, dialog.plotInfo.workstation_detail[0].C_Numerator, dialog.plotInfo.workstation_detail[0].C_Denominator);
                                                        calcDialog.hide();
                                                    }
                                                }

                                                angular.element(target).removeClass('is-focus');

                                            }
                                        },
                                        function(calcDialog){
                                            angular.element(target).removeClass('is-focus');
                                            calcDialog.hide();
                                        },
                                        {
                                            defaultNum : trackOutQty,
                                            decimal : true
                                        });

                                },
                                trackOutBack: function () {
                                    dialog.hide();
                                },
                                //出站確認
                                trackOutConfirm: function(){
                                    if(dialog.isRequire){
                                        $rootScope.showAlert($filter('translate')('B0206.msg.production_inf_require'), function(){
                                            dialog.openProductionInfPage();
                                        });
                                    } else {
                                        SMES_AccLifeCheck(machine_no, dialog.plotInfo, function(){
                                            ProductionParametersCheckProcess(dialog);
                                        });
                                    }
                                },
                                //開啟不良原因
                                openBadPage:function(){
                                    var content = {
                                        op_no : dialog.plotInfo.workstation_detail[0].op_no
                                    };
                                    $MMWService.sendToSMESServer({
                                        uri : 'tcsmes.GetData.QCReasonBasis',
                                        content : content,
                                        success : function(data){
                                            if (data.Result != 'fail') {
                                                dialog.badTypeList = genBadType(data.qc_reason_basis);
                                                badCodeList = data.qc_reason_basis;
                                                dialog.mode = 'badReason';
                                                dialog.tmpBadReason = {};
                                                dialog.tmpBadType = '';
                                                dialog.tmpBadTypeName = '';
                                                dialog.tmpAbnormal_qty = '';
                                                //備份當時的不明原因列表
                                                badReasonInfo_backup = dialog.badReasonInfo.slice();
                                            } else {
                                                $rootScope.showAlert(data.SysMsg);
                                            }
                                        }
                                    });
                                },
                                loadBadTypeList: function(){
                                    $rootScope.showSelect({
                                        label: 'reason_sub_type',
                                        code: 'reason_type',
                                        selectCode: dialog.tmpBadType,
                                        list: dialog.badTypeList,
                                        confirm: function (item, radioDialog) {
                                            radioDialog.hide();
                                            dialog.tmpBadType = item.reason_type;
                                            dialog.tmpBadTypeName = item.reason_sub_type;
                                        }
                                    });
                                },
                                loadBadReasonList: function(){
                                    if(dialog.tmpBadType != ''){
                                        $rootScope.showQueryList({
                                            key:'reason_no',
                                            title:$filter('translate')('common.queryList.badReason_select'),
                                            header : [
                                                {label: $filter('translate')('common.queryList.reason_c'), code:'reason_no'},
                                                {label: $filter('translate')('common.queryList.reason_n'), code:'reason_name'}
                                            ],
                                            query: function(conditions, feedback){
                                                feedback($filter('filter')(badCodeList, {reason_type:dialog.tmpBadType}));
                                            },
                                            confirm: function(selectItem, radioDialog){
                                                radioDialog.hide();
                                                dialog.tmpBadReason = selectItem;
                                            }
                                        });
                                    } else {
                                        $rootScope.showAlert($filter('translate')('B0206.msg.bad_type_empty'));
                                    }
                                },
                                //新增不良原因
                                addBadReason: function(){
                                    if(!dialog.tmpBadReason.reason_name){
                                        $rootScope.showAlert($filter('translate')('B0206.showAlert.column3'),function(){
                                            dialog.tmpBadType = '';
                                            dialog.tmpBadTypeName = '';
                                            dialog.tmpBadReason = {};
                                            dialog.tmpAbnormal_qty = '';
                                        });
                                    }else{
                                        if(dialog.tmpAbnormal_qty>0){
                                            dialog.badReasonInfo.push({
                                                plot_no: dialog.plotInfo.workstation_detail[0].plot_no,
                                                abnormal_type : dialog.tmpBadReason.reason_type ,
                                                abnormal_type_name : dialog.tmpBadReason.reason_sub_type,
                                                abnormal_no : dialog.tmpBadReason.reason_no ,
                                                abnormal_name : dialog.tmpBadReason.reason_name,
                                                defect_qty: dialog.tmpAbnormal_qty,
                                            });
                                            dialog.tmpBadType = '';
                                            dialog.tmpBadTypeName = '';
                                            dialog.tmpBadReason = {};
                                            dialog.tmpAbnormal_qty = '';
                                            //console.log(dialog.badReasonInfo);
                                        }else{
                                            $rootScope.showAlert($filter('translate')('B0206.showAlert.column4'),function(){
                                                dialog.tmpAbnormal_qty = '';
                                            });
                                        }
                                    }
                                },
                                //刪除不良原因
                                removeBadReason : function(item){
                                    dialog.badReasonInfo.splice(dialog.badReasonInfo.indexOf(item), 1);
                                },
                                //不良原因-確定
                                badReasonConfirm : function(){
                                    var total_surplus_qty = 0;//多餘數
                                    var total_abnormal_qty = 0; //報廢
                                    var total_lack_qty = 0;//短少
                                    dialog.badReasonInfo.forEach(function(info){
                                        if(info.abnormal_type == '11'){
                                            total_surplus_qty = $calculater.decimalAdd(total_surplus_qty, (+info.defect_qty));
                                        } else if(info.abnormal_type == '12'){
                                            total_lack_qty = $calculater.decimalAdd(total_lack_qty, (+info.defect_qty));
                                        } else {
                                            total_abnormal_qty =  $calculater.decimalAdd(total_abnormal_qty, (+info.defect_qty));
                                        }
                                    });
                                    if((total_surplus_qty + dialog.plotInfo.qty)<(total_abnormal_qty+total_lack_qty)){
                                        $rootScope.showAlert($filter('translate')('B0206.showAlert.column5')+dialog.plotInfo.qty);
                                    }else{
                                        dialog.plotInfo.total_surplus_qty = total_surplus_qty;//多餘數
                                        dialog.plotInfo.total_abnormal_qty = total_abnormal_qty; //報廢
                                        dialog.plotInfo.total_lack_qty = total_lack_qty;//短少
                                        //2018051601 modify by Dustdusk for M#45925:
                                        //物料使用量 = 『良品』 + 『不良品』 + 『短少』 = 『出站數量』 + 『多餘』
                                        var sum_qty = $calculater.decimalAdd((+dialog.plotInfo.qty),(+dialog.plotInfo.total_surplus_qty));
                                        for(var i=0; i<plotInfo.workstation_detail[0].materials_detail.length; i++){
                                            plotInfo.workstation_detail[0].materials_detail[i].use_qty =
                                                $calculater.decimalMutiple(sum_qty, plotInfo.workstation_detail[0].materials_detail[i].std_use_qty, 6);
                                        }
                                        //2018051601 modify by Dustdusk for M#45925:
                                        //良品數 = 『出站數量』 - 『不良品』 - 『短少』 + 『多餘』
                                        dialog.plotInfo.good_qty =  $calculater.decimalSub($calculater.decimalSub($calculater.decimalAdd((+dialog.plotInfo.qty), (+dialog.plotInfo.total_surplus_qty)), (+dialog.plotInfo.total_abnormal_qty)), (+dialog.plotInfo.total_lack_qty));
                                        dialog.plotInfo.workstation_detail[0].QTYACIO = CaculatQTYACIO(dialog.plotInfo.good_qty, dialog.plotInfo.workstation_detail[0].C_Numerator, dialog.plotInfo.workstation_detail[0].C_Denominator);
                                        dialog.mode='trackOut';
                                    }

                                },
                                //不良原因，取消
                                badReasonCancel: backToTrackOut,

                                //進入多人產量登入
                                openMultiplePage:function(){
                                    dialog.mode = 'multiple';
                                    labor_detail_backup = angular.merge([],dialog.plotInfo.workstation_detail[0].labor_detail);
                                },
                                addMultipleLabor: function(labor_no, labor_name){
                                    var labor_detail = dialog.plotInfo.workstation_detail[0].labor_detail;
                                    var isExist = false;
                                    for(var i = 0; i < labor_detail.length; i++){
                                        if(labor_detail[i].labor_no == labor_no){
                                            isExist = true;
                                            break;
                                        }
                                    }
                                    if(!isExist){
                                        labor_detail.push({labor_no: labor_no, labor_name: labor_name, qty: plotInfo.qty, labor_time: 0});
                                    }else{
                                        $rootScope.showAlert($filter('translate')('B0206.msg.labor_no_exist', {labor_no: labor_no})); //人員已存在
                                    }
                                    dialog.tmpLabor_no = '';
                                },
                                deleteMultipleLabor: function(item){
                                    $rootScope.showConfirm($filter('translate')('B0206.msg.is_delete_multiple_labor', {labor_name: item.labor_name}),
                                        function(confirmDialog){
                                            confirmDialog.hide();
                                            var index = dialog.plotInfo.workstation_detail[0].labor_detail.indexOf(item);
                                            dialog.plotInfo.workstation_detail[0].labor_detail.splice(index, 1);
                                        }
                                    );
                                },
                                searchLabor: function(event){
                                    if(!event || event.keyCode==13){
                                        if(dialog.tmpLabor_no!=''){
                                            var content = {
                                                machine_no : machine_no,
                                                employee_no : dialog.tmpLabor_no,
                                                report_datetime : new Date(),
                                                return_type : '10'
                                            };

                                            $MMWService.sendToServer({
                                                uri: 'ServicesSTD.Module_SYS.user_information_get',
                                                content : content,
                                                success : function(data){
                                                    dialog.addMultipleLabor(data.employee_no, data.employee_name);
                                                },
                                                error:function(data){
                                                    $rootScope.showAlert(data.Message, function(){
                                                        document.getElementById('tmpLabor_no').focus();
                                                    });
                                                }
                                            });
                                        }else{
                                            $rootScope.showAlert($filter('translate')('B0206.msg.input_labor_empty'), function(){
                                                document.getElementById('tmpLabor_no').focus();
                                            });
                                        }
                                    }
                                },
                                laborInputQty : function(event, labor){
                                    var target = event.currentTarget;
                                    angular.element(target).addClass('is-focus');
                                    $calculater.open(function(num,calcDialog){
                                        if((+num) > (+dialog.plotInfo.qty)){
                                            $rootScope.showAlert($filter('translate')('B0206.showAlert.column6')+dialog.plotInfo.qty);
                                        } else {
                                            calcDialog.hide();
                                            angular.element(target).removeClass('is-focus');
                                            labor.qty = num;
                                        }
                                    },
                                    function(calcDialog){
                                        angular.element(target).removeClass('is-focus');
                                        calcDialog.hide();
                                    },
                                    {
                                        defaultNum : labor.qty,
                                        decimal : true
                                    });
                                },
                                multipleCheck: function(){
                                    var msg = '';
                                    var labor_detail = dialog.plotInfo.workstation_detail[0].labor_detail;
                                    if(labor_detail.length == 0){
                                        msg = $filter('translate')('B0206.msg.labor_detail_empty'); //人員明細不可為空
                                    } else {
                                        for(var i = 0; i < labor_detail.length; i++){
                                            if(labor_detail[i].labor_time == 0 && labor_detail[i].qty == 0){
                                                msg = $filter('translate')('B0206.msg.qty_and_labor_time_is_empty'); //數量與人時不可同時為0。
                                                break;
                                            }
                                        }
                                    }
                                    return msg;
                                },
                                multipleConfirm:function(){
                                    var msg = dialog.multipleCheck();
                                    if(msg == ''){
                                        //計算總人時
                                        dialog.plotInfo.workstation_detail[0].labor_hours = 0;
                                        dialog.plotInfo.workstation_detail[0].number_of_labor = 0;
                                        dialog.plotInfo.workstation_detail[0].labor_detail.forEach(function(labor){
                                            dialog.plotInfo.workstation_detail[0].labor_hours = $calculater.decimalAdd(dialog.plotInfo.workstation_detail[0].labor_hours, labor.labor_time);
                                            dialog.plotInfo.workstation_detail[0].number_of_labor += 1;
                                        });
                                        dialog.mode='trackOut';
                                    } else {
                                        $rootScope.showAlert(msg);
                                    }
                                },
                                multipleCancel:backToTrackOut,
                                //進入生產資訊收集
                                openProductionInfPage:function(){
                                    if(dialog.plotInfo.production_inf_detail && dialog.plotInfo.production_inf_detail.length>0){
                                        dialog.mode = 'production_inf';
                                        dialog.production_inf_detail = dialog.plotInfo.production_inf_detail;
                                        production_inf_detail_backup = angular.merge([],dialog.plotInfo.production_inf_detail);
                                    } else {
                                        $rootScope.showAlert($filter('translate')('B0206.showAlert.production_inf_detail_empty'));
                                    }
                                },
                                switchInit: function(item){
                                    if(!item.productioninf_value){
                                        item.productioninf_value = '0';
                                    }
                                },
                                switchClick: function(item){
                                    if(item.productioninf_value == '0'){
                                        item.productioninf_value = '1' ;
                                    } else {
                                        item.productioninf_value = '0';
                                    }
                                },
                                productionInfConfirm:function(){
                                    var msg = '';
                                    if(dialog.plotInfo.production_inf_type == '2'){
                                        msg = productionInfValidate(dialog.production_inf_detail);
                                    }
                                    if(msg == ''){
                                        dialog.isRequire = false;
                                        dialog.mode='trackOut';
                                    } else {
                                        dialog.isRequire = true;
                                        $rootScope.showAlert(msg);
                                    }
                                },
                                loadMachineList:function(){
                                    //設備清單
                                    $rootScope.showQueryList({
                                        header: [
                                            {label:$filter('translate')('common.queryList.machine_c'), code:'page_no'},
                                            {label:$filter('translate')('common.queryList.machine_n'), code:'page_name'}
                                        ],
                                        query: function(conditions, feedback){
                                            //20180525 modify by 李栋 for mantis#0047129
                                            $MMWService.sendToSMESServer({
                                                uri: 'tcSMES.clsSMES.page_number_info_get_json',
                                                content : {
                                                    page_mode: 2,
                                                    query_condition_info:[
                                                        {column_type:'11', query_mode:'1', value: 'WIP_TYPE', merge_condition_model: 'AND'}
                                                    ]
                                                },
                                                success : function(data){
                                                    // var temp = $filter('filter')(data.page_number_info_get, {favourite:'1'});
                                                    var temp = data.page_number_info_get;
                                                    if(temp && temp.length){
                                                        feedback(temp);
                                                    }
                                                }
                                            });
                                        },
                                        selectCode: dialog.plotInfo.machine_no_wip || '',
                                        confirm : function(selectItem, queryDialog){
                                            dialog.plotInfo.machine_no_wip = selectItem.page_no;
                                            queryDialog.hide();
                                        }
                                    });
                                }
                            }
                        }
                    );
                }
            };
        }]);
});
